package com.ruoyi.web.controller.robot;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.WXHttpUtils;
import com.ruoyi.common.utils.WXPartnerJsapiPrepay;
import com.ruoyi.common.utils.WXPayUtility;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/*
 *@title RobotWXController
 *@description
 *@author wanghaohao
 *@version 1.0
 *@create 2025-10-23 10:57
 */
@Controller
public class RobotWXController {

    //测试用的AppID(小程序ID): wxb436e168f15aec48
    //测试用的AppSecret(小程序密钥)：5c5b3ad3dc76c658f258f9dc7522ea85
    //微信接口获取失败的时候的返回：{"errcode":40163,"errmsg":"code been used, rid: 68f99fe1-1424a905-79945198"}
    //微信接口获取成功的时候的返回：{"session_key":"2vxN/iE+Tg2lFdJ+yXMmog==","openid":"ohm7v4nIIoGhnlkXhrq5hiK3pq_0"}
    // avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
    @PostMapping("/wx/codeToOpenID")
    @Anonymous
    @ResponseBody
    public AjaxResult codeToOpenID(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @RequestParam String jsCode) {
        try {
            String result = WXHttpUtils.jscode2session(UserConstants.WECHAT_MINIPROGRAM_APP_ID, UserConstants.WECHAT_MINIPROGRAM_APP_SECRET, jsCode);
            if (result.contains("errcode")) {
                return AjaxResult.error("OpenID获取失败！").put("result", result);
            }

            JSONObject jsonObject = JSON.parseObject(result);
            return AjaxResult.success("OpenID获取成功！")
                    .put("result", result)
                    .put("session_key", jsonObject.getString("session_key"))
                    .put("openid", jsonObject.getString("openid"));
        } catch (Exception e) {
            return AjaxResult.error("OpenID获取失败！");
        }
    }

    /**
     * 创建微信支付订单
     *
     * @param orderNo     商户订单号
     * @param totalAmount 订单总金额(元)
     * @param openid      微信用户openid
     * @param productName 商品名称
     * @return 支付订单信息
     */
    @PostMapping("/wx/createPayment")
    @Anonymous
    @ResponseBody
    public AjaxResult createPayment(@RequestParam String orderNo,
                                    @RequestParam BigDecimal totalAmount,
                                    @RequestParam String openid,
                                    @RequestParam String productName) {
        try {
            // 构建微信支付请求参数
            Map<String, Object> requestParams = new HashMap<>();
            // 微信支付必要参数（根据实际业务调整）
            requestParams.put("sp_appid", UserConstants.WECHAT_MINIPROGRAM_APP_ID);
//            requestParams.put("sp_mchid", UserConstants.WECHATPAY_MCH_ID); // 需要在UserConstants中添加商户号常量
            requestParams.put("out_trade_no", orderNo);
            requestParams.put("description", productName);

            // 构建支付者信息
            Map<String, Object> payer = new HashMap<>();
            payer.put("openid", openid);
            requestParams.put("payer", payer);

            // 构建金额信息（微信支付金额单位为分）
            Map<String, Object> amount = new HashMap<>();
            amount.put("total", totalAmount.multiply(new BigDecimal("100")).intValue());
            requestParams.put("amount", amount);

            // 调用微信支付接口（实际项目中需要生成正确的Authorization签名）
            String authorization = ""; // 此处需要替换为实际生成的微信支付签名
            String response = WXHttpUtils.sendJSAPIPost(authorization, requestParams);

            // 解析支付响应结果
            JSONObject resultJson = JSON.parseObject(response);
            return AjaxResult.success("支付订单创建成功").put("paymentInfo", resultJson);
        } catch (Exception e) {
            return AjaxResult.error("支付订单创建失败: " + e.getMessage());
        }
    }

    /**
     * 微信支付结果通知回调接口
     * 官方文档：https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_5.shtml
     */
    @PostMapping("/pay/notify")
    public Object wxpayNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 1. 获取通知报文
            String signature = request.getHeader("Wechatpay-Signature");
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String serialNo = request.getHeader("Wechatpay-Serial");
            String body = WXPayUtility.readRequestBody(request);

            // 2. 验证签名（使用微信支付平台证书）
            boolean isValid = WXPayUtility.verifySignature(
                    serialNo,
                    timestamp,
                    nonce,
                    body,
                    signature,
                    WXPayUtility.loadPublicKeyFromPath("")
            );

//            if (!isValid) {
//                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
//                return Map.of("code", "FAIL", "message", "签名验证失败");
//            }
//
//            // 3. 解析通知内容
//            WXPartnerJsapiPrepay.PartnerAPIv3PartnerJsapiPrepayResponse notifyData =
//                    WXPayUtility.fromJson(body, WXPartnerJsapiPrepay.PartnerAPIv3PartnerJsapiPrepayResponse.class);
//
//            // 4. 处理业务逻辑（示例）
//            if ("SUCCESS".equals(notifyData.tradeState)) {
//                // TODO: 更新订单状态、记录支付信息等业务操作
//                System.out.println("支付成功，订单号：" + notifyData.outTradeNo);
//            }
//
//            // 5. 返回成功响应（必须返回200状态码和指定格式）
//            response.setStatus(HttpServletResponse.SC_OK);
//            return Map.of("code", "SUCCESS", "message", "成功");

            return new Object();

        } catch (Exception e) {
            // 6. 错误处理
//            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//            return Map.of("code", "FAIL", "message", "处理失败：" + e.getMessage());

            return new Object();
        }
    }
}
